//
//  NetDownloadManager.m
//  NetworkDemo
//
//  Created by InitialC on 2017/5/22.
//  Copyright © 2016年 InitialC. All rights reserved.
//

#import "NetDownloadManager.h"
#import "SVProgressHUD.h"
#import "MGJRouter.h"
#ifdef DEBUG
#define NetCLog(...) NSLog(__VA_ARGS__)
#else
#define NetCLog(...)
#endif
@interface NetDownloadManager ()
@property(nonatomic,copy)DownloadProgress progress;
@end

@implementation NetDownloadManager
- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (NSDictionary *)dictionaryWithModel {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"url"] = self.url?: @"";
    if (self.progress) {
        dic[@"DownloadProgress"] = self.progress;
    }
    dic[@"savePath"] = self.savePath?: @"";
    dic[@"type"] = @"download";
    
    return dic;
    
}
- (void)request:(DownloadProgress )progress completion: (void(^)(id result))complete {
    [self request: progress completion: complete withFailure: nil];
}
- (void)request:(DownloadProgress )progress completion: (void(^)(id result))complete withFailure: (void(^)(NSError *error))fail {
    if (progress) {
        self.progress = progress;
    }
    
    [MGJRouter openURL: BaseGeneralRequest withUserInfo: [self dictionaryWithModel] completion: ^(id result) {
        if( [SVProgressHUD isVisible]) {
            [SVProgressHUD dismiss];
        }
        if (([result isKindOfClass: [NSError class]])) {
            NetCLog(@"网络下载错误 = %@",result);
            if(self.isShowFaildError)
            {
                [SVProgressHUD showErrorWithStatus: [result domain]];
            }
            if (fail) {
                fail(result);
            }
        } else {
            //            - (BOOL)moveItemAtPath: (NSString *)srcPath toPath: (NSString *)dstPath error: (NSError *)error
            NSString *string = result[@"filePath"];
            //从路径中获得完整的文件名 （带后缀）
            NSString *fileName = [string lastPathComponent];
            
            NSString *pathExtension = [string pathExtension];
            if (self.fileName != nil) {
                //修改名字
                fileName = [string stringByReplacingOccurrencesOfString: fileName withString: [NSString stringWithFormat: @"%@.%@",self.fileName,pathExtension]];
                
                NSError *error = nil;
                //判断文件是否存在，存在删除文件
                if([[NSFileManager defaultManager] fileExistsAtPath: [fileName stringByReplacingOccurrencesOfString: @"file://" withString: @""]])
                {
                    [[NSFileManager defaultManager] removeItemAtURL: [NSURL URLWithString: fileName] error: &error];
                }
                //修改文件名
                if ([[NSFileManager defaultManager] moveItemAtURL: [NSURL URLWithString: string] toURL: [NSURL URLWithString: fileName] error: &error] == YES)
                {
                    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary: result];
                    dic[@"filePath"] = fileName;
                    result = dic;
                    
                }
            }
            complete(result);
        }
    }];
    
}
@end
